package utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
    定义C3P0Util工具类,从C3P0连接池中获取连接Connection对象
 */
/*public class C3P0Util {
    //创建C3P0连接池的对象,内部存储了多个Connection对象
    //创建对象时,会自动读取src根目录下的配置文件,怎么读取的,不用关心
    //静态方法直接分配内存，非静态要等对象实例化才分配内存
    private static ComboPooledDataSource cpds = new ComboPooledDataSource();

    private C3P0Util(){

    }
    //定义静态方法,获取Connection对象
    public static Connection getConnection() throws SQLException {
        //连接池对象,调用getConnection()方法,获取连接Connection对象
        return cpds.getConnection();
    }
    //定义静态方法,获取连接池对象
    public static DataSource getDataSource() {
        return cpds;
    }

    //释放资源
    public static void release(Connection con, Statement stmt, ResultSet rs) {
        //4.关闭资源
        if(con!=null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}*/
public class C3P0Util {
    public C3P0Util() {}
    //创造连接池对象。会自动获取配置文件中配置的数据库信息，自动创建连接，获取sql语句对象
    private  static  ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();

    //创建Connection对象的实现类getConnection，返回Datasoure数据源实现的实现类ComboPooledDataSource重写的getConnection方法
    public  static Connection getConnection() throws SQLException {
        return  comboPooledDataSource.getConnection();
    }
    //返回接口DataSource的实现类对象
    public  static  DataSource getDataSource(){
        return  comboPooledDataSource;
    }

    public static  void release(Connection connection,Statement statement,ResultSet resultSet){
        if(connection !=null){
           try{
               connection.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
        }
        if(statement !=null){
            try{
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet !=null){
            try{
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}